package com.ovolucky.mapmytrip.app.place;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by wanghuifang on 7/9/14.
 */
public class PlaceJsonParser {

  /** Receives a JSONObject and returns a list */
  public static List<HashMap<String,String>> parse(JSONObject jsonObject){

    JSONArray places = null;
    try {
      /** Retrieves all the elements in the 'places' array */
      places = jsonObject.getJSONArray("predictions");
    } catch (JSONException e) {
      e.printStackTrace();
    }
    /** Invoking getPlaces with the array of json object
     * where each json object represent a place
     */
    return getPlaces(places);
  }

  private static List<HashMap<String, String>> getPlaces(JSONArray places){
    int placesCount = places.length();
    List<HashMap<String, String>> placesList = new ArrayList<>();
    HashMap<String, String> place;

    /** Taking each place, parses and adds to list object */
    for(int i=0; i<placesCount; i++){
      try {
        /** Call getPlace with place JSON object to parse the place */
        place = getPlace((JSONObject)places.get(i));
        placesList.add(place);

      } catch (JSONException e) {
        e.printStackTrace();
      }
    }

    return placesList;
  }

  /** Parsing the Place JSON object */
  private static HashMap<String, String> getPlace(JSONObject jsonPlace){

    HashMap<String, String> place = new HashMap<>();

    String id;
    String reference;
    String description;

    try {
      description = jsonPlace.getString("description");
      id = jsonPlace.getString("id");
      reference = jsonPlace.getString("reference");

      place.put("description", description);
      place.put("_id",id);
      place.put("reference",reference);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return place;
  }
}